<template>
    <div id="app">
        <el-header style="background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
            <div class="header-content">
                <h3>AI智能管理系统</h3>
                <div class="user-info">
                    <el-avatar :size="30" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"/>
                    <span>欢迎，{{ username }}</span>
                </div>
            </div>
        </el-header>

        <!-- 实时登录信息横条 -->
        <div class="real-time-login-bar">
            <div class="login-stats">
                <div class="stat-item">
                    <el-icon><User /></el-icon>
                    <div class="stat-info">
                        <div class="stat-value">{{ liveData.today }}</div>
                        <div class="stat-label">今日登录</div>
                    </div>
                </div>
                <div class="stat-item">
                    <el-icon><Monitor /></el-icon>
                    <div class="stat-info">
                        <div class="stat-value">{{ liveData.online }}</div>
                        <div class="stat-label">当前在线</div>
                    </div>
                </div>
                <div class="stat-item">
                    <el-icon><TrendCharts /></el-icon>
                    <div class="stat-info">
                        <div class="stat-value">{{ liveData.weekly }}</div>
                        <div class="stat-label">7日活跃</div>
                    </div>
                </div>
            </div>
            <div ref="liveChart" class="live-chart"></div>
        </div>

        <div class="container">
            <el-main style="padding: 20px;">
                <div class="dashboard-container">
                    <!-- 新增的每日在线用户折线图 -->
                    <div class="module-section">
                        <h4>用户活跃度统计</h4>
                        <div class="chart-row">
                            <div class="chart-card full-width">
                                <h5>每日在线用户数</h5>
                                <div ref="dailyUsersChart" style="width: 100%; height: 400px;"></div>
                            </div>
                        </div>
                    </div>

                    <div class="module-section">
                        <h4>管理模块统计</h4>
                        <div class="chart-row">
                            <div class="chart-card">
                                <h5>模型分布</h5>
                                <div ref="modelsChart" style="width: 100%; height: 300px;"></div>
                            </div>
                            <div class="chart-card">
                                <h5>问题数量</h5>
                                <div ref="questionsChart" style="width: 100%; height: 300px;"></div>
                            </div>
                        </div>
                        <div class="chart-row">
                            <div class="chart-card">
                                <h5>反馈处理状态</h5>
                                <div ref="feedbackChart" style="width: 100%; height: 300px;"></div>
                            </div>
                            <div class="chart-card">
                                <h5>活动类型统计</h5>
                                <div ref="activityTypeChart" style="width: 100%; height: 300px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-main>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { noPageListModels } from "@/api/models/models"
import { nopagelistQuestions } from "@/api/questions/questions"
import { noPagelistFeedback } from "@/api/feedback/feedback"
import { listActivityType } from "@/api/activityType/activityType"
import { noPageListActivity } from "@/api/activity/activity"
import { User, Monitor, TrendCharts } from '@element-plus/icons-vue'

const username = ref('管理员')
const modelsChart = ref(null)
const questionsChart = ref(null)
const feedbackChart = ref(null)
const activityTypeChart = ref(null)
const dailyUsersChart = ref(null) // 新增的每日用户图表引用

// 实时数据相关
const liveChart = ref(null)
const liveData = ref({
    today: '1,428',
    online: '356',
    weekly: '5,231'
})

// 生成过去30天的日期数据
const generateDateLabels = () => {
    const dates = []
    const now = new Date()
    for (let i = 29; i >= 0; i--) {
        const date = new Date(now)
        date.setDate(date.getDate() - i)
        dates.push(`${date.getMonth() + 1}/${date.getDate()}`)
    }
    return dates
}

// 初始化每日用户图表
const initDailyUsersChart = () => {
    if (!dailyUsersChart.value) return

    const chart = echarts.init(dailyUsersChart.value)
    const dates = generateDateLabels()
    const onlineData = dates.map(() => Math.floor(Math.random() * 500) + 200)
    const activeData = dates.map(() => Math.floor(Math.random() * 800) + 300)
    const newUserData = dates.map(() => Math.floor(Math.random() * 100) + 50)

    const option = {
        title: {
            text: '每日用户数据',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            }
        },
        legend: {
            data: ['在线用户数', '活跃用户数', '新增用户数'],
            top: 30
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: dates,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '在线用户数',
                type: 'line',
                stack: '总量',
                smooth: true,
                lineStyle: {
                    width: 0
                },
                showSymbol: false,
                areaStyle: {
                    opacity: 0.8,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(58, 77, 233, 0.8)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(58, 77, 233, 0.1)'
                        }
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: onlineData
            },
            {
                name: '活跃用户数',
                type: 'line',
                stack: '总量',
                smooth: true,
                lineStyle: {
                    width: 0
                },
                showSymbol: false,
                areaStyle: {
                    opacity: 0.8,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(0, 221, 255, 0.8)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(0, 221, 255, 0.1)'
                        }
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: activeData
            },
            {
                name: '新增用户数',
                type: 'line',
                stack: '总量',
                smooth: true,
                lineStyle: {
                    width: 0
                },
                showSymbol: false,
                areaStyle: {
                    opacity: 0.8,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(255, 0, 135, 0.8)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(255, 0, 135, 0.1)'
                        }
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: newUserData
            }
        ]
    }

    chart.setOption(option)
    window.addEventListener('resize', () => chart.resize())
}

// 初始化实时图表
const initLiveChart = () => {
    if (!liveChart.value) return

    const chart = echarts.init(liveChart.value)
    const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)
    const data = hours.map(() => Math.floor(Math.random() * 200) + 50)

    chart.setOption({
        grid: {
            left: 0,
            right: 0,
            top: 0,
            bottom: 0
        },
        xAxis: {
            type: 'category',
            data: hours,
            show: false
        },
        yAxis: {
            type: 'value',
            show: false
        },
        series: [{
            data: data,
            type: 'line',
            smooth: true,
            symbol: 'none',
            lineStyle: {
                width: 2,
                color: '#fff'
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(255,255,255,0.3)' },
                    { offset: 1, color: 'rgba(255,255,255,0.1)' }
                ])
            }
        }]
    })

    window.addEventListener('resize', () => {
        chart.resize()
    })
}

// 其他数据获取方法保持不变
const fetchActivityTypeData = async () => {
    try {
        const [typesRes, activitiesRes] = await Promise.all([
            listActivityType({}),
            noPageListActivity({})
        ])

        const activityTypes = typesRes.data || typesRes.rows || []
        const activities = activitiesRes.rows || []

        const topLevelTypes = activityTypes.filter(type => type.parentId === 0 || type.parentId === '0')

        const typeTree = topLevelTypes.map(topType => {
            const subTypes = activityTypes.filter(type => type.parentId == topType.id)
            const topTypeActivities = activities.filter(activity => activity.typeId == topType.id)

            const subTypeCounts = subTypes.map(subType => {
                const subTypeActivities = activities.filter(activity => activity.typeId == subType.id)
                return {
                    id: subType.id,
                    name: subType.name,
                    count: subTypeActivities.length
                }
            })

            return {
                id: topType.id,
                name: topType.name,
                count: topTypeActivities.length,
                children: subTypeCounts
            }
        })

        return typeTree
    } catch (error) {
        console.error('获取活动类型数据失败:', error)
        return []
    }
}

const fetchModelsData = async () => {
    try {
        const res = await noPageListModels({})
        const data = res.rows || []
        const modelCounts = {}

        data.forEach(item => {
            const name = item.name || '未知模型'
            modelCounts[name] = (modelCounts[name] || 0) + 1
        })

        return Object.entries(modelCounts).map(([name, value]) => ({ name, value }))
    } catch (error) {
        console.error('获取模型数据失败:', error)
        return []
    }
}

const fetchModelList = async () => {
    try {
        const res = await noPageListModels({})
        return res.rows || []
    } catch (error) {
        console.error('获取模型列表失败:', error)
        return []
    }
}

const fetchQuestionsData = async () => {
    try {
        const [modelList, questionRes] = await Promise.all([
            fetchModelList(),
            nopagelistQuestions({})
        ])

        const modelMap = {}
        modelList.forEach(model => {
            modelMap[model.id] = model.name
        })

        const data = questionRes.rows || []
        const questionCounts = {}

        data.forEach(item => {
            const categoryId = item.categoryId
            const categoryName = modelMap[categoryId] || '未分类'
            questionCounts[categoryName] = (questionCounts[categoryName] || 0) + 1
        })

        return Object.entries(questionCounts).map(([name, value]) => ({ name, value }))
    } catch (error) {
        console.error('获取问题数据失败:', error)
        return []
    }
}

const fetchFeedbackData = async () => {
    try {
        const res = await noPagelistFeedback({})
        const data = res.rows || []
        const feedbackStats = {
            processed: 0,
            unprocessed: 0
        }

        data.forEach(item => {
            if (item.status === 1) {
                feedbackStats.processed++
            } else {
                feedbackStats.unprocessed++
            }
        })

        return [
            { name: '已处理', value: feedbackStats.processed },
            { name: '未处理', value: feedbackStats.unprocessed }
        ]
    } catch (error) {
        console.error('获取反馈数据失败:', error)
        return []
    }
}

// 初始化模型分布图表 - 玫瑰图
const initModelsChart = (dom, data) => {
    if (!dom) return

    const chart = echarts.init(dom)
    const option = {
        title: {
            text: '模型分布',
            left: 'center',
            top: 0
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 30,
            bottom: 0,
            data: data.map(item => item.name)
        },
        series: [{
            name: '模型分布',
            type: 'pie',
            radius: [20, 100],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
                borderRadius: 5,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: false
            },
            emphasis: {
                label: {
                    show: true
                }
            },
            data: data
        }]
    }

    chart.setOption(option)
    window.addEventListener('resize', () => chart.resize())
    return chart
}

// 初始化问题数量图表 - 柱状图
const initQuestionsChart = (dom, data) => {
    if (!dom) return

    const chart = echarts.init(dom)
    const option = {
        title: {
            text: '问题数量',
            left: 'center',
            top: 0
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: data.map(item => item.name),
            axisLabel: {
                interval: 0,
                rotate: 30
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            name: '问题数量',
            type: 'bar',
            barWidth: '60%',
            data: data.map(item => item.value),
            itemStyle: {
                color: function(params) {
                    const colorList = [
                        '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae',
                        '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570'
                    ]
                    return colorList[params.dataIndex % colorList.length]
                }
            }
        }]
    }

    chart.setOption(option)
    window.addEventListener('resize', () => chart.resize())
    return chart
}

// 初始化反馈处理状态图表 - 环形图
const initFeedbackChart = (dom, data) => {
    if (!dom) return

    const chart = echarts.init(dom)
    const option = {
        title: {
            text: '反馈处理状态',
            left: 'center',
            top: 0
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 30,
            bottom: 0,
            data: data.map(item => item.name)
        },
        series: [{
            name: '反馈状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
                borderRadius: 5,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '18',
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: data
        }]
    }

    chart.setOption(option)
    window.addEventListener('resize', () => chart.resize())
    return chart
}

// 初始化活动类型统计图表 - 雷达图
const initActivityTypeChart = (dom, data) => {
    if (!dom) return

    // 准备雷达图数据
    const indicator = []
    const seriesData = []

    data.forEach(topType => {
        indicator.push({ name: topType.name, max: topType.count + 10 })
        seriesData.push(topType.count)

        topType.children.forEach(subType => {
            indicator.push({ name: subType.name, max: subType.count + 10 })
            seriesData.push(subType.count)
        })
    })

    const chart = echarts.init(dom)
    const option = {
        title: {
            text: '活动类型统计',
            left: 'center',
            top: 0
        },
        tooltip: {
            trigger: 'item'
        },
        radar: {
            indicator: indicator,
            radius: '65%',
            splitNumber: 4,
            axisName: {
                color: '#333'
            },
            splitArea: {
                areaStyle: {
                    color: ['rgba(26, 152, 255, 0.1)', 'rgba(26, 152, 255, 0.2)',
                        'rgba(26, 152, 255, 0.4)', 'rgba(26, 152, 255, 0.6)',
                        'rgba(26, 152, 255, 0.8)', 'rgba(26, 152, 255, 1)'],
                    shadowColor: 'rgba(0, 0, 0, 0.2)',
                    shadowBlur: 10
                }
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(26, 152, 255, 0.5)'
                }
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(26, 152, 255, 0.5)'
                }
            }
        },
        series: [{
            name: '活动数量',
            type: 'radar',
            data: [{
                value: seriesData,
                name: '活动数量',
                areaStyle: {
                    color: 'rgba(26, 152, 255, 0.4)'
                },
                lineStyle: {
                    width: 2
                },
                symbolSize: 6
            }]
        }]
    }

    chart.setOption(option)
    window.addEventListener('resize', () => chart.resize())
    return chart
}

onMounted(async () => {
    await nextTick()

    // 初始化实时图表
    initLiveChart()

    // 初始化每日用户图表
    initDailyUsersChart()

    // 获取数据并初始化图表
    const [modelsData, questionsData, feedbackData, activityTypeData] = await Promise.all([
        fetchModelsData(),
        fetchQuestionsData(),
        fetchFeedbackData(),
        fetchActivityTypeData()
    ])

    initModelsChart(modelsChart.value, modelsData)
    initQuestionsChart(questionsChart.value, questionsData)
    initFeedbackChart(feedbackChart.value, feedbackData)
    initActivityTypeChart(activityTypeChart.value, activityTypeData)

    // 模拟实时数据更新
    setInterval(() => {
        liveData.value = {
            today: (parseInt(liveData.value.today.replace(/,/g, '')) + Math.floor(Math.random() * 3)).toString(),
            online: (parseInt(liveData.value.online.replace(/,/g, '')) + Math.floor(Math.random() * 5 - 2)).toString(),
            weekly: (parseInt(liveData.value.weekly.replace(/,/g, '')) + Math.floor(Math.random() * 10)).toString()
        }

        // 格式化数字
        Object.keys(liveData.value).forEach(key => {
            liveData.value[key] = liveData.value[key].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        })

        initLiveChart()
    }, 3000)
})
</script>

<style scoped>
#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    color: #2c3e50;
    min-height: 100vh;
    background-color: #f5f7fa;
}

.container {
    display: flex;
    padding-top: 10px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 60px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.dashboard-container {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.module-section h4 {
    font-size: 18px;
    margin-bottom: 20px;
    color: #333;
}

.chart-row {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-top: 20px;
}

.chart-card {
    flex: 1;
    min-width: 300px;
    background: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    height: 400px;
}

.chart-card.full-width {
    flex: 0 0 100%;
    min-width: 100%;
}

.chart-card h5 {
    margin: 0 0 10px 0;
    color: #409EFF;
    font-size: 16px;
    text-align: center;
}

@media (max-width: 1200px) {
    .chart-card {
        min-width: calc(50% - 20px);
    }
}

@media (max-width: 768px) {
    .chart-card {
        min-width: 100%;
    }
}

/* 实时登录信息横条样式 */
.real-time-login-bar {
    background: linear-gradient(90deg, #1a2980, #26d0ce);
    color: white;
    padding: 12px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.login-stats {
    display: flex;
    gap: 30px;
}

.stat-item {
    display: flex;
    align-items: center;
    gap: 12px;
}

.stat-info {
    display: flex;
    flex-direction: column;
}

.stat-value {
    font-size: 20px;
    font-weight: bold;
}

.stat-label {
    font-size: 12px;
    opacity: 0.8;
}

.live-chart {
    width: 250px;
    height: 60px;
    margin-right: 20px;
}

@media (max-width: 768px) {
    .real-time-login-bar {
        flex-direction: column;
        gap: 15px;
    }

    .login-stats {
        width: 100%;
        justify-content: space-around;
        gap: 15px;
    }

    .live-chart {
        width: 100%;
        margin-right: 0;
    }
}
</style>